﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.SessionState;

namespace WebApplication
{
	public class Validate : IHttpHandler, IRequiresSessionState
	{
		public void ProcessRequest(HttpContext context)
		{
			string code = CreateRandomCode(4);
			context.Session["ValidateCode"] = code;
			
			context.Response.ClearContent();
			context.Response.ContentType = "image/jpeg";
			context.Response.BinaryWrite(CreateImage(code).ToArray());
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}

		private string CreateRandomCode(int codeCount)
		{
			string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
			string[] allCharArray = allChar.Split(',');
			string randomCode = "";
			int temp = -1;

			Random rand = new Random();
			for (int i = 0; i < codeCount; i++)
			{
				if (temp != -1)
				{
					rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
				}
				int t = rand.Next(35);
				if (temp == t)
				{
					return CreateRandomCode(codeCount);
				}
				temp = t;
				randomCode += allCharArray[t];
			}
			return randomCode;
		}

		private System.IO.MemoryStream CreateImage(string checkCode)
		{
			int width = (int)(checkCode.Length * 11.5);
			Bitmap image = new Bitmap(width, 20);
			Graphics graphic = Graphics.FromImage(image);
			Font font = new  Font("Arial", 10, FontStyle.Bold);
			Brush brush = new SolidBrush(Color.White);
			//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
			graphic.Clear(Color.Blue);
			graphic.DrawString(checkCode, font, brush, 3, 3);

			Pen blackPen = new Pen(Color.Black, 0);
			Random rand = new Random();
			for (int i = 0; i < 5; i++)
			{
				int y = rand.Next(image.Height);
				graphic.DrawLine(blackPen, 0, y, image.Width, y);
			}

			MemoryStream ms = new MemoryStream();
			image.Save(ms, ImageFormat.Jpeg);
			graphic.Dispose();
			image.Dispose();

			return ms;
		}
	}
}